
import { useUserStore } from '@/stores/user'
import axios, { type Method } from 'axios'

const instance = axios.create({
  baseURL: 'http://geek.itheima.net/',
  timeout: 20 * 1000
})

export interface ServerResponse<T>{
message:string
data:T
}


// 封装工具函数
export const request = <T>(url:string,method : Method='GET',submitData?:object)=>{
return instance.request<T,ServerResponse<T>>({
  url,
  method,
  [method.toLowerCase()==='get'?'params':'data']:submitData
})
}


// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 获取token
    const token = useUserStore();
    // 如果有token自动添加到请求头中
    if (token.token) {
      config.headers.Authorization = `Bearer ${token.token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);


// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 相应拦截器，减少了一层data,直接获取后端返回类型
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);



export default instance
